package com.vf.cloud.paas.app.master.api.project.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.project.service.IProjectClassify;
import com.vf.cloud.paas.app.master.common.domain.Project;
import com.vf.cloud.paas.app.master.common.domain.ProjectClassify;

@Service
public class ProjectClassifyImpl implements IProjectClassify {

	public List<ProjectClassify> getChildrens(ProjectClassify param) {
		if(!StrKit.isBlank(param.getName())) {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+ProjectClassify.TABLE_NAME+" WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM "+ProjectClassify.TABLE_NAME+"  T WHERE T.PID=?  and t.name like '%"+param.getName()+"%'   ORDER BY T.SORT ASC";
			return ProjectClassify.dao.find(sql, param.getPid());
		}else {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+ProjectClassify.TABLE_NAME+" WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM "+ProjectClassify.TABLE_NAME+"  T WHERE T.PID=?    ORDER BY T.SORT ASC";
			return ProjectClassify.dao.find(sql, param.getPid());
		}
	}
	
	public List<ProjectClassify> getChildren(ProjectClassify param) {
		List<ProjectClassify> ProjectClassifys = ProjectClassify.dao.find("select * from " + ProjectClassify.TABLE_NAME + " where pid=? ", param.getId());
		for (ProjectClassify p : ProjectClassifys) {
			p.setChildren(getChildren(p));
		}
		return ProjectClassifys;
	}

	@Override
	public void delete(String id) {
		 deleteChildrens(id);
	}

	public void deleteChildrens(String id) {
		List<ProjectClassify> projectClassifys = ProjectClassify.dao.find("select id from "+ProjectClassify.TABLE_NAME+" where pid=? ",id);
		for (ProjectClassify classify : projectClassifys) {
			if(classify.delete()) {
				deleteChildrens(classify.getId());
				Db.delete("delete From "+Project.TABLE_NAME+" where classify_id=? ",classify.getId());
			}
		}
		Db.delete("delete from master_user_project where project_id in (select id from "+Project.TABLE_NAME+"  where classify_id=? ) ",id);
		Db.delete("delete from api_test_custom where project_id in (select id from "+Project.TABLE_NAME+"  where classify_id=? ) ",id);
		Db.delete("delete From "+Project.TABLE_NAME+" where classify_id=? ",id);
		ProjectClassify.dao.deleteById(id);
	}

}
